const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');



router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});

// 读取文件路由
router.get('/read', (req, res) => {
    // 假设data文件夹下的文件名为test.txt
    const filePath = path.join(__dirname, '../data/test.txt');
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            res.status(500).send('Error reading file');
        } else {
            res.send(data);
        }
    });
});

// 写入文件路由
const cors = require('cors');
router.use(cors());
router.post('/write', (req, res) => {
    const data = req.body;
    const filePath = path.join(__dirname, '../data/test.txt');
    fs.writeFile(filePath, JSON.stringify(data), 'utf8',(err) => {
        if (err) {
            console.error(err);
            res.status(500).send('Error writing file');
        } else {
            res.send('Data written successfully');
        }
    });
});

module.exports = router;